package org.example.transaction.controller;


import jakarta.annotation.sql.DataSourceDefinition;
import org.example.transaction.TransactionApplication;
import org.example.transaction.service.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/user")
public class LoginController {


    //jdbc事务管理器
    @Autowired
    private DataSourceTransactionManager dataSourceTransactionManager;

    //事务的属性
    @Autowired
    private TransactionDefinition transactionDefinition;


    @Autowired
    private UserInfoService userInfoService;

    @RequestMapping("/Login")
    public String login(String userName,String password){
        //定义事务
        //可以理解为在这个时间点进行存档，回滚到这个时间点
        TransactionStatus transactionStatus = dataSourceTransactionManager.getTransaction(transactionDefinition);

        Integer n = userInfoService.insertUserInfo(userName,password);
        System.out.println("影响的行数："+n);

        //提交事务
        //不提交事务，数据添加失败
        dataSourceTransactionManager.commit(transactionStatus);

        //回滚
        //回滚到定义的时间点
//        dataSourceTransactionManager.rollback(transactionStatus);
        return "增加成功";
    }
}
